<!-- src/view/borrow_records.vue -->
<template>
  <div>
    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top: 20px">
      <el-form-item label="用户">
        <el-input v-model="searchObj.user_id" placeholder="请输入用户ID" clearable :disabled="!isAdmin" />
      </el-form-item>

      <el-form-item label="书籍名">
        <el-input v-model="searchObj.book_id" placeholder="请输入书籍名称" clearable />
      </el-form-item>

      <el-form-item label="状态">
        <select v-model="searchObj.is_return">
          <option value="1">已归还</option>
          <option value="0">未归还</option>
          <option value="">全部</option>
        </select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%">

      <el-table-column label="用户" width="80" v-if="isAdmin">
        <template #default="scope">
          <span>{{ scope.row.user.user_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="书籍名" width="180">
        <template #default="scope">
          {{scope.row.book.book_name}}
        </template>
      </el-table-column>

      <el-table-column label="借阅时间" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.create_time) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="归还时间" width="180">
        <template #default="scope">
          <span>{{ scope.row.return_time ? formatDate(scope.row.return_time) : '未归还' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.is_return === 1 ? 'success' : 'warning'">
            {{ scope.row.is_return === 1 ? '已归还' : '未归还' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" >
        <template #default="scope">
          <el-button
              v-if="scope.row.is_return === 0"
              size="small"
              type="success"
              @click="handleReturn(scope.row)">
            还书
          </el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <el-pagination
        style="margin-top:20px"
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/util/request.js'
import api from '@/api/borrow_api.js'

// 定义绑定的数据
const tableData = ref([])
const searchObj = ref({
  current: 1,
  limit: 10,
  user_id: null,
  book_id: '',
  is_return: null
})
const total = ref(0)
const isAdmin = ref(false)
const currentUserId = ref(null)

// 获取用户信息
const getUserInfo = async () => {
  try {
    const response = await request({
      url: '/api/login/logininfo',
      method: 'get'
    })
    currentUserId.value = response.id
    isAdmin.value = response.user_role === 1
    // 如果不是管理员，只显示当前用户的记录
    if (!isAdmin.value) {
      searchObj.value.user_id = currentUserId.value
    }
    search()
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 查询借阅记录
const search = async () => {
  try {
    const params = {
      current: searchObj.value.current,
      limit: searchObj.value.limit
    }

    if (searchObj.value.user_id) {
      params.user_id = searchObj.value.user_id
    }

    if (searchObj.value.book_id) {
      params.book_id = searchObj.value.book_id
    }

    if (searchObj.value.is_return !== null && searchObj.value.is_return !== '') {
      params.is_return = searchObj.value.is_return
    }

    const response = await request({
      url: '/api/borrow/page',
      method: 'get',
      params
    })

    tableData.value = response.data.map(item => ({
      ...item,
      book_id: item.book_id || '未知书籍'
    }))
    total.value = response.count
  } catch (error) {
    ElMessage.error('查询失败: ' + (error.message || '未知错误'))
  }
}

// 页面加载后要挂载的数据
onMounted(async () => {
  await getUserInfo()
})

// 定义方法
const handleSizeChange = () => {
  search()
}

const handleCurrentChange = () => {
  search()
}

const handlerSearch = () => {
  searchObj.value.current = 1
  search()
}

// 时间格式化函数
const formatDate = (dateString) => {
  if (!dateString) return ''

  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return dateString
  }
}

// 还书操作
const handleReturn = (row) => {
  ElMessageBox.confirm(
      `确认归还书籍《${row.book_name || '未知书籍'}》吗？`,
      '还书确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await request({
        url: '/api/borrow/return',
        method: 'post',
        params: {
          borrowId: row.id
        }
      })
      search()
    } catch (error) {
      ElMessage.error('还书失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {
    // 用户取消操作
  })
}
</script>

<style scoped>
</style>
